package com.sourcetrip.arraylist;


import com.sourcetrip.raw.model.Student;

import java.io.*;

/**
 * @author: ZhouBert
 * @date: 2020/11/16
 * @description:	测试 Serializable 接口
 * 记住这几个类与 Serializable 的关系
 * ObjectOutputStream#writeObject
 * ObjectInputStream#readObject
 * 当 model 没有实现 Serializable 接口时，序列化 writeObject 时就会抛出异常：
 * java.io.NotSerializableException: model.Student
 *
 */
public class SerTest01 {

	/**
	 * 文件路径名
	 */
	public static final String FILE_PATH = "M:\\research\\openjdk8reading\\src\\main\\java\\openjdk\\test\\a.txt";

	public static void main(String[] args) throws IOException, ClassNotFoundException {

		//调用写数据的方法
		writeObject();
		//调用读数据的方法
		readObject();
	}

	/**
	 * 定义方法将对象数据写入文件
	 * @throws IOException
	 */
	private static void writeObject() throws IOException {
		//创建对象操作流 --> 序列化（将dui）
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_PATH));
		Student s1 = new Student("青青", 32);
		oos.writeObject(s1);
		oos.close();
	}

	/**
	 * 定义方法将问价的数据读取出来
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	private static void readObject() throws IOException, ClassNotFoundException {
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_PATH));
		Student s1 = (Student) ois.readObject();
		System.out.println("s1.getName() = " + s1.getName());
		ois.close();
	}
}
